// read json from json.zip

const jsonFiles = {};

const JSZip = require('jszip-sync');

function getJson(name: string): any {
	return jsonFiles[name];
}

function getJsonFromZip(file: string) {
	// return getJson(file.substr(0,file.length-5)); //remove .json
	return getJson(file);
}

let loadedJson = false;
async function initJson(): Promise<void> {
	const t1 = getServerTimems();
	console.log('init_json');
	const zipdata: any = await server.LoadDataByUrl('xls/xls.zip', RES.ResourceItem.TYPE_BIN);
	if (!zipdata) {
		console.error("error! LoadDataByUrl('xls/xls.zip')");
		return;
	}
	const t2 = getServerTimems();
	console.log('download xls.zip ok', t2 - t1);

	// const txtdata: any = await server.LoadDataByUrl('xls/xls.txt',RES.ResourceItem.TYPE_TEXT);
	// console.log("download xls.txt ok",txtdata.length)
	const t3 = getServerTimems();

	// let JSZip = require("jszip")
	const zipjson = new JSZip();
	zipjson.sync(function () {
		zipjson.loadAsync(zipdata).then(function () {
			// console.log("load zip file ok",t3-t2)
			const keys = Object.keys(zipjson.files);
			for (const name of keys) {
				// let  tt = getServerTimems();
				zipjson
					.file(name)
					.async('text')
					.then(function (data: any) {
						// let tt2 = getServerTimems();
						// console.log("unzip data", tt2-tt)
						jsonFiles[name] = JSON.parse(data);
						// console.log("json parse",  getServerTimems()-tt2)
					});
			}
		});
	});

	loadedJson = true;
	const t4 = getServerTimems();
	console.log('loadJson end', t4 - t3);
}

function isLoadedJson(): boolean {
	return loadedJson;
}
